package quick.start.core.config;

import java.util.HashMap;

import org.apache.commons.lang3.ArrayUtils;

import android.util.Log;

public class ConfigureMan {
    private static final String LOG_TAG = "ConfMan";
    protected static final String LOG_PATTERN = "Key %s expected %s but value was a %s. The default value %s was returned.";
    private HashMap<String, Object> mConfTable;

    public void init(IConfigure... confs) {
        mConfTable = new HashMap<String, Object>();
        if (ArrayUtils.isEmpty(confs)) return;
        for (IConfigure conf : confs) {
            mConfTable.putAll(conf.getConfigure());
        }
    }

    public <T> T getPrimitive(String key, Class<T> cls, T defaultValue) {
        Object o = mConfTable.get(key);
        if (o == null) return defaultValue;

        try {
            return cls.cast(o);
        } catch (ClassCastException e) {
            typeWarning(key, o, cls.getName(), defaultValue, e);
            return defaultValue;
        }
    }

    public int getInt(String key) {
        return getPrimitive(key, Integer.class, 0);
    }

    public long getLong(String key) {
        return getPrimitive(key, Long.class, 0l);
    }

    public double getDouble(String key) {
        return getPrimitive(key, Double.class, 0.0d);
    }

    public String getString(String key) {
        return getPrimitive(key, String.class, null);
    }

    public boolean getBoolean(String key) {
        return getPrimitive(key, Boolean.class, false);
    }

    private void typeWarning(String key, Object value, String className, Object defaultValue, ClassCastException e) {
        Log.w(LOG_TAG, String.format(LOG_PATTERN, key, className, value.getClass().getName(), (null == defaultValue) ? "<null>" : defaultValue));
        Log.w(LOG_TAG, "Attempt to cast generated internal exception:", e);
    }
}
